package com.kwm.filter;
import com.kwm.entity.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*") // 设置拦截路径，代表所有拦截
public class DemoFilter implements Filter {
    //初始化方法
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    // 每次拦截到请求会触发
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI().toString();

        if (url.contains("login")){

            log.info("登录请求，直接放行");
            filterChain.doFilter(request,response);

            return;
        }

        String jwt = request.getHeader("token");

        if(jwt == null){

            log.info("获取令牌为空，返回错误结果");
            response.setStatus(401);
            return;
        }
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {

            e.printStackTrace();
            log.info("解析令牌失败，返回错误结果");

            return;
        }

        log.info("令牌合法，放行");
        filterChain.doFilter(request,response);

    }
    //销毁方法，只在服务器关闭的时候触发一次
    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
